package com.example.demo.Controller;

import com.example.demo.entity.Userinfo;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
     private DataSourceTransactionManager transactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;

    @RequestMapping("/add")
    public int add(Userinfo userinfo){

        if(userinfo==null || !StringUtils.hasLength(userinfo.getUsername())
        ||!StringUtils.hasLength(userinfo.getPassword() ))
        {
            return 0;
        }

        //开始事务
        TransactionStatus transactionStatus=transactionManager.getTransaction(transactionDefinition);


        userinfo.setCreatetime(LocalDateTime.now().toString());

        int result=userService.add(userinfo);
        System.out.println(result);
//        //回滚事务
//        transactionManager.rollback(transactionStatus);

        //提交事务
        transactionManager.commit(transactionStatus);
        return result;
    }

    @RequestMapping("/insert")
    @Transactional//事务注释，自动提交。错误就回滚
    public Integer insert(Userinfo userinfo)
    {
        if(userinfo==null || !StringUtils.hasLength(userinfo.getUsername())
                ||!StringUtils.hasLength(userinfo.getPassword() ))
        {
            return 0;
        }

        int result=userService.add(userinfo);
        System.out.println(result);

        try {
            int num=10/0;
        } catch (Exception e) {
            //打印异常
            System.out.println(e.getMessage());
            //手动回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }
}
